import './index.scss'
import 'devextreme/dist/css/dx.material.blue.light.compact.css'
import { useRequest } from 'alova/client'
import { Input, Button, Space } from 'antd'
import { lazy, Suspense, useEffect, useState } from 'react'
import { useMount, useTitle, useFavicon, useEventEmitter } from 'ahooks'

import { Http } from '../Utils/Api'
import { ModelBox, DrawerBox } from '../Model'
import { LockPageA01 } from '../Page/Other/LockPage'
import { themeStore, pageStore } from '../Config/zustand'
import { themeMapping, loadCSS } from '../Config/devMapping'
import { GetIndexedDB, AddIndexdDB, PutIndexedDB } from '../Utils/IndexedDB'


const LoadSvg = lazy(() => import('../Page/Loading/LoadSvg'))

const AdminInit = () => {
    const TITLE = sessionStorage.getItem('TITLE')
    const IMAGE_URL = sessionStorage.getItem('IMAGE')
    useTitle(TITLE)
    useFavicon(IMAGE_URL + 'Ico.ico')
    const { updateActive, updateList } = pageStore()
    const { theme, updateTheme, updateLogo, updateMenu, updateHead, updateBody } = themeStore()

    const [Theme, setTheme] = useState()
    const [MaskStatus, setMaskStatus] = useState(false)

    const [UnlockPwd, setUnlockPwd] = useState()
    const [PwdStatus, setPwdStatus] = useState()

    const { send } = useRequest(data => Http(data), { immediate: false })


    useMount(async () => {
        const dev = sessionStorage.getItem('dev')
        const config = await GetIndexedDB('config')
        const project = await GetIndexedDB('project')
        const token = await GetIndexedDB('token')
        const user = await GetIndexedDB('user')
        const openKey = await GetIndexedDB('openKey')
        const pageList = await GetIndexedDB('pageList')
        const menuList = await GetIndexedDB('menu')
        const powerList = await GetIndexedDB('power')
        const userAdd = await GetIndexedDB('userAdd')
        const lock = await GetIndexedDB('lock')
        setMaskStatus(lock || false)

        // console.log('[config]', config)
        // console.log('[project]', project)
        // console.log('[token]', token)
        // console.log('[user]', user)
        // console.log('[openKey]', openKey)
        // console.log('[pageList]', pageList)
        // console.log('[menuList]', menuList)
        // console.log('[powerList]', powerList)
        // 分配项目配置信息
        const { theme, logo, menu, head, body } = project
        updateTheme(theme)
        updateLogo(logo)
        updateMenu(menu)
        updateHead(head)
        updateBody(body)
        updateActive(openKey)
        updateList(pageList)
        // loadCSS(themeMapping.find(v => v.value === dev).css)
    })

    useEffect(() => {
        if (theme.template) {
            const ThemeTemp = lazy(() => import(`./theme/${theme.template}.jsx`))
            setTheme(ThemeTemp)
        }
    }, [theme.template])

    const onLock = async () => {
        const lock = await GetIndexedDB('lock')
        if (lock === false) await PutIndexedDB('lock', true)
        if (lock === undefined) await AddIndexdDB('lock', true)
        setMaskStatus(true)
    }

    const onUnlock = async () => {
        send({ method: 'post', url: 'users/verifyPassword', params: { OldPassword: UnlockPwd } }).then(res => {
            PutIndexedDB('lock', false)
            setMaskStatus(false)
            setPwdStatus()
        }).catch(() => {
            setPwdStatus('error')
        })
    }

    const CallBackFunc = (e) => {
        // console.log('CallBackFunc', e)
        const { type, data } = e
        const MapReturn = new Map([
            ['openMask', () => onLock()],
            ['offMask', () => onUnlock()]
        ])
        const func = MapReturn.get(type)
        return func && func()
    }

    const AdminEvent = useEventEmitter()
    AdminEvent.useSubscription(CallBackFunc)

    return (
        <Suspense>
            {Theme ? <Theme AdminEvent={AdminEvent} /> : <div></div>}
            <ModelBox />
            <DrawerBox />
            {MaskStatus &&
                <div className='largeMask' >
                    <LockPageA01 />
                    <div className='Unlock' >
                        <div className='InputBox'>
                            <Space.Compact >
                                <Input.Password
                                    placeholder='请用登录密码解锁'
                                    size='large'
                                    status={PwdStatus}
                                    variant="filled"
                                    onChange={e => setUnlockPwd(e.target.value)}
                                />
                                <Button size='large' type='primary' onClick={onUnlock}>解锁</Button>
                            </Space.Compact >
                        </div>
                    </div>
                </div>
            }
        </Suspense>
    );
};

export default AdminInit